<%@page import="mydb.MyDB"%>
<%@page import="java.util.concurrent.*"%>
<%@page import="java.sql.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8" session="false" %>

<%
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
%>
<%
    /*
     CREATE TABLE IF NOT EXISTS `test` (
     `id` bigint(20) NOT NULL,
     `value` bigint(20) NOT NULL,
     `msg` varchar(255) COLLATE utf8_bin NOT NULL,
     PRIMARY KEY (`id`)
     ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
     */
%>
<%    synchronized (MyDB.testLock) {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://"
                + System.getenv("MOPAAS_MYSQL25292_HOSTNAME") + ":"
                + System.getenv("MOPAAS_MYSQL25292_PORT") + "/"
                + System.getenv("MOPAAS_MYSQL25292_NAME") + "?user="
                + System.getenv("MOPAAS_MYSQL25292_USER") + "&password="
                + System.getenv("MOPAAS_MYSQL25292_PASSWORD")
                + "&characterEncoding=utf-8";
        //out.println(url);

        Connection conn = DriverManager.getConnection(url);
        try {
            conn.setAutoCommit(false);
            ResultSet rs = conn.createStatement().executeQuery("select count(id) from test");
            while (rs.next()) {
                if (rs.getInt(1) == 0) {
                    PreparedStatement stmt = conn.prepareStatement(
                            "INSERT INTO `test`(`id`, `value`, `msg`) VALUES (?,?,?)"
                    );
                    for (int i = 1; i <= 10000; i++) {
                        stmt.setLong(1, i);
                        stmt.setLong(2, i * 2);
                        stmt.setString(3, i
                                + "既方既皂，既坚既好，不稂不莠。去其螟螣，及其蟊贼，无害我田稚. --螟螣and蟊贼 2 types of bug");
                        stmt.addBatch();
                    }
                    stmt.executeBatch();
                }
            }
            conn.commit();
        } finally {
            conn.close();
        }

        Connection[] cs = new Connection[10];
        ExecutorService es = Executors.newFixedThreadPool(cs.length);
        Future<Integer>[] fs = new Future[cs.length];
        for (int i = 0; i < cs.length; i++) {
            cs[i] = DriverManager.getConnection(url);
        }
        try {
            long begin = System.currentTimeMillis();
            for (int i = 0; i < cs.length; i++) {
                final Connection c = cs[i];
                fs[i] = es.submit(
                        new Callable<Integer>() {
                            public Integer call() throws Exception {
                                ResultSet rs = c.createStatement()
                                .executeQuery("select `id`, `value`, `msg` from test");
                                int l = 0;
                                while (rs.next()) {
                                    if (rs.getString(3).startsWith(
                                            Integer.toString(rs.getInt(1))
                                    )) {
                                        l += rs.getInt(2);
                                    }
                                }
                                return l;
                            }
                        }
                );
            }
            long count = 0;
            for (int i = 0; i < cs.length; i++) {
                count += fs[i].get();
            }
            out.println(System.currentTimeMillis() - begin + "," + count);
        } finally {
            for (int i = 0; i < cs.length; i++) {
                cs[i].close();
            }
        }
        es.shutdown();
        es = null;
        System.gc();
    }

%>
